package per.jdz.demo.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: yyyy-MM-dd easyExcel 日期转换
 */
@Slf4j
public class DateConverter implements Converter<Date> {

    private static final String PATTERN_YYYY_MM_DD = "yyyy-MM-dd";

    @Override
    public Class<?> supportJavaTypeKey() {
        return Converter.super.supportJavaTypeKey();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return Converter.super.supportExcelTypeKey();
    }

    /**
     * 这里读的时候会调用
     *
     * @param context
     * @return
     */
    @Override
    public Date convertToJavaData(ReadConverterContext<?> context) {
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        String dataStr = context.getReadCellData().getStringValue();
//        String dateValue = sdf.format(dataStr);
//        System.out.println(context.getReadCellData().getStringValue());
        try {
            // 解析字符串为 Date 对象
            Date date = sdf.parse(dataStr);
//            System.out.println("转换后的日期: " + date);
            return date;
        } catch (Exception e) {
//            System.out.println(dataStr);
            return null;
        }
    }


    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Date> context)  {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
            String dateValue = sdf.format(context.getValue());
            return new WriteCellData<>(dateValue);
            // 解析字符串为 Date 对象
        } catch (Exception e) {
            log.error(e.getMessage());
            return new WriteCellData<>("");
        }
    }
}